<template>
    <page-meta :page-style="$theme.pageStyle">
		<!-- #ifndef H5 -->
		<navigation-bar
			:front-color="$theme.navColor"
			:background-color="$theme.navBgColor"
		/>
		<!-- #endif -->
	</page-meta>
    <up-loading-page loading-text="loading..." :loading="loading"></up-loading-page>
	<view class="bg-white min-h-full flex flex-col items-center px-[40rpx] pt-[80rpx] box-border">
		
		<view class="mt-[100rpx] text-center">
			<view class="text-2xl font-bold">男友驱动法则</view>
			<view class="text-muted mt-[30rpx]">哄哄就好了</view>
		</view>
		<view class="mt-[140rpx] w-full">
			<view v-if="isWeixin">
				<button type="primary" class="primary text-lg text-white leading-[80rpx] h-[80rpx] mb-[50rpx]" @click="wxLogin()">
					用户一键登录
				</button>
			</view>
			<view v-else>
				<view class="text-center" @click="goPage('/pages/login_account/index')">
					手机号登录
				</view>
			</view>

		</view>
		<mplogin-popup type="bottom" :show="showLoginPopup" border-radius="14" title="男友使用指南" @update="handleUpdateUser">
        </mplogin-popup>
	</view>
</template>

<script setup lang="ts">
	import { mnpLogin, updateUser } from "@/api/account";
	import { BACK_URL } from "@/enums/cacheEnums";
	import { useAppStore } from "@/stores/app";
	import { useUserStore } from "@/stores/user";
	import cache from "@/utils/cache";
	import { isWeixinClient } from "@/utils/client";
	// #ifdef H5
	import wechatOa from "@/utils/wechat";
	// #endif
	import { onLoad, onReady, onShow } from "@dcloudio/uni-app";
	import { computed, ref } from "vue";
	import {useRouter} from "uniapp-router-next";

	const isWeixin = ref(true);
    const loading = ref(true);
	// #ifdef H5
	isWeixin.value = isWeixinClient();
	// #endif

	const userStore = useUserStore();
	const appStore = useAppStore();

	const showLoginPopup = ref(false);
	const loginData = ref();

	const isOpenThirdAuth = computed(() => appStore.config.third_auth == 1);
	const isOpenWechatAuth = computed(() => appStore.config.wechat_auth == 1);
	const isForceBindMobile = computed(() => appStore.config.coerce_mobile == 1)


	const wxLogin = async () => {
        		
		// #ifdef MP-WEIXIN
		uni.showLoading({
			title: "请稍后...",
		});
		try {
			const { code } : any = await uni.login({
				provider: "weixin",
			});
			const data = await mnpLogin({
				code: code,
			});
			loginData.value = data;
			if (data.is_new_user) {
				uni.hideLoading();
				userStore.temToken = data.token;
                console.log("login ok")
                uni.showToast({
                    title: '登陆成功',
                    duration: 2000
                });
				showLoginPopup.value = true;
				return;
			}
			loginHandle(data);
		} catch (error : any) {
			uni.hideLoading();
            uni.showToast({
                title: 'error',
                duration: 2000
            });
		}
		// #endif
		// #ifdef H5
		if (isWeixin.value) {
			wechatOa.getUrl();
		}
		// #endif
	};

	const loginHandle = async (data : any) => {
		// const { token, mobile } = data;
        // // 强制验证手机号
		// if (!mobile && isForceBindMobile.value) {
		// 	userStore.temToken = token;
		// 	uni.navigateTo({
		// 		url: "/pages/bind_mobile/index",
		// 	});
		// 	uni.hideLoading();
		// 	return;
		// }
		// userStore.login(data.token);
		await userStore.getUser();
		// uni.showToast({
        //     title: '登陆成功',
        //     duration: 2000
        // });
        routeTo();
	};

	const goPage = (url : string) => {
		uni.navigateTo({
			url: url
		});
	};

	const handleUpdateUser = async (value : any) => {
		await updateUser(value, { token: userStore.temToken });
		showLoginPopup.value = false;
		loginHandle(loginData.value);
	};

	onLoad(async ()=> {
        // #ifdef MP-WEIXIN
        wx.reportEvent("login", {})
        // #endif
        await userStore.getUser();
        // #ifdef MP-WEIXIN
        wx.reportEvent("login_comp", {})
        // #endif
        const data = userStore.userInfo;
        if (data.is_new_user) {
            showLoginPopup.value = true;
            return;
        }
		// 已登录，跳转首页
		if (userStore.isLogin) {
			routeTo();
			return;
		}
		// 非公众号H5，跳转账号登录页面
		// #ifdef H5
		// if (!isWeixin.value) {
		// 	uni.redirectTo({
		// 		url: "/pages/login_account/index?type="+(appStore.config.login_way[0] || 1),
		// 	});
		// 	return;
		// }
        // console.log('login',options)
		// const { code } = options;
		// if (code) {
		// 	uni.showLoading({
		// 		title: "请稍后...",
		// 	});
		// 	//用于清空code

		// 	try {
		// 		const data = await wechatOa.authLogin(code);
		// 		loginHandle(data);
		// 	} catch (error : any) {
		// 		uni.hideLoading();
		// 		throw new Error(error);
		// 	}
		// } else {
		// 	// 未开启第三方登录，跳转到账号登录
		// 	if (!isOpenThirdAuth.value || !isOpenWechatAuth.value) {
		// 		uni.redirectTo({
		// 			url: "/pages/login_account/index",
		// 		});
		// 		return;
		// 	}
		// }
		// #endif
        // #ifdef MP-WEIXIN
            wxLogin()
        // #endif
	});


    const routeTo = () => {
        loading.value = false;
        const router = useRouter()
        console.log('routeTo',router)
        // #ifdef APP-PLUS
        // app 模式,直接返回
		// router.navigateBack()
		// #endif


		// #ifndef APP-PLUS
		const pages = getCurrentPages()
		if (pages.length > 1) { //历史记录
			const prevPage = pages[pages.length - 2]
            console.log("return last page",prevPage)
			// router.navigateBack()
            //TODO 
			// @ts-ignore
			const {onLoad, options} = prevPage
			// 刷新上一个页面
			onLoad && onLoad(options)
            return
		} 
        var url = '/pages/index/index';
        if (cache.get(BACK_URL)) { //缓存
            url = cache.get(BACK_URL)
            cache.remove(BACK_URL)
            try {
            // router.redirectTo(url)
            uni.redirectTo({
                url
            })
            } finally {
                uni.switchTab({
                    url
                })
                // router.switchTab(url)
            }
            return;
		} else { //啥也没有
			const options = uni.getLaunchOptionsSync()
            if(options.query.share_code){
                url = '/pages/work/index?share_code='+options.query.share_code
                uni.redirectTo({
                    url
                })
                return
            }
		}
        uni.switchTab({
            url
        })
		// #endif
    }
</script>

<style lang="scss">
	page {
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.footer {
		left: 0;
		bottom: 0;
		width: 100%;
		height: 120rpx;
		position: fixed;
		z-index: 1;
		display: flex;
		justify-content: center;
	}
</style>